import React, { useState, useRef, useContext, useEffect } from 'react';
import { SendOutlined, FileZipOutlined, CloudTwoTone, LoadingOutlined } from '@ant-design/icons';
import { Card, Flex, message, Spin, Button } from 'antd';
import axios from 'axios';
import { AuthContext } from '../../contexts/AuthContext';
import './index.css'
import { useTranslation } from 'react-i18next';

const UploadFolder = ({ onUploadSuccess }) => {
    const { t } = useTranslation();
    const [selectedFileName, setSelectedFileName] = useState(t('仅支持 ZIP 和 TAR.GZ 格式'));
    const fileInputRef = useRef(null);
    const { token, username } = useContext(AuthContext);
    const [uploadLoading, setUploadLoading] = useState(false);
    const [messageApi, contextHolder] = message.useMessage();
    const handleFileSelect = (e) => {
        const files = e.target.files;
        if (files && files.length > 0) {
            const fileName = files[0].name;
            if (!fileName.endsWith('.zip') && !fileName.endsWith('.tar.gz')) {
                message.error('仅支持 ZIP 和 TAR.GZ 格式');
                setSelectedFileName('支持 .zip 和 .tar.gz 格式文件');
                e.target.value = '';
                return;
            }
            setSelectedFileName(`已选择文件: ${fileName}`);
        } else {
            setSelectedFileName('支持 .zip 和 .tar.gz 格式文件');
        }
    };
    const handleUploadButtonClick = async () => {
        const fileInput = fileInputRef.current;
        if (!fileInput?.files?.length) {
            message.warning(t('先选择文件'));
            return;
        }

        setUploadLoading(true);
        const file = fileInput.files[0];
        const fileName = file.name;

        if (!fileName.toLowerCase().endsWith('.zip') && !fileName.toLowerCase().endsWith('.tar.gz')) {
            message.error('仅支持 ZIP 和 TAR.GZ 格式');
            setUploadLoading(false);
            return;
        }

        const formData = new FormData();
        formData.append('file', file);

        try {
            setUploadLoading(true);
            const response = await axios.post('/api/v1/pkg/upload', formData, {
                headers: {
                    'Authorization': token,
                }
            });
            console.log(response.data);

            if (response.data.code === 0) {
                messageApi.success(t('成功'));
                onUploadSuccess();
            } else if ([1003, 1001, 1002].includes(response.data.code)) {
                            message.error(t('Token失效，请重新登录'))
                            localStorage.removeItem('username');
                            localStorage.removeItem('enc_token');
                            localStorage.removeItem('privilege_level');
                            navigate('/login');
                        }
        } catch (error) {
            messageApi.error(t('失败'));
        } finally {
            setUploadLoading(false);
            fileInputRef.current.value = '';
            setSelectedFileName(t('支持 .zip 和 .tar.gz 格式文件'));
        }
    };
    return (
        <>
            {contextHolder}
            <Card hoverable style={{ marginBottom: 10, height: 260 }}>
                <Flex vertical justify="space-between" style={{ paddingTop: 10 }}>
                    <div className="upload-header">
                        <h2><CloudTwoTone /> {t("上传软件包")}</h2>
                        <p className="file-hint">{selectedFileName}</p>
                    </div>
                    <div className="file-input-wrapper">
                        <div className="custom-file-input">
                            <input
                                type="file"
                                id="fileInput"
                                accept=".zip, .tar.gz"
                                ref={fileInputRef}
                                onChange={handleFileSelect}
                                style={{ display: 'none' }}
                            />
                            <label htmlFor="fileInput" className="upload-btn">
                                <FileZipOutlined />&nbsp;{t("选择文件")}
                            </label>
                        </div>
                    </div>
                    <button
                        className="upload-btn2 upload-btn"
                        onClick={handleUploadButtonClick}
                        disabled={uploadLoading}
                    >
                        {uploadLoading ? (
                            <span>
                                <LoadingOutlined size="small" style={{ marginRight: 8 }} />
                                {t("上传中...")}
                            </span>
                        ) : (
                            <span>
                                <SendOutlined />&nbsp;{t("开始上传")}
                            </span>
                        )}
                    </button>
                </Flex>
            </Card>
        </>
    );
};

export default UploadFolder;